import { ref, computed } from 'vue'

// 全局状态管理
const currentUser = ref(null)
const userPermissions = ref([])

export const useAuth = () => {
  // 登录
  const login = (userInfo) => {
    currentUser.value = userInfo
    userPermissions.value = getUserPermissions(userInfo.role)
    localStorage.setItem('currentUser', JSON.stringify(userInfo))
    localStorage.setItem('userPermissions', JSON.stringify(userPermissions.value))
  }

  // 登出
  const logout = () => {
    currentUser.value = null
    userPermissions.value = []
    localStorage.removeItem('currentUser')
    localStorage.removeItem('userPermissions')
  }

  // 初始化用户信息
  const initAuth = () => {
    // 开发模式：自动设置为系统管理员
    if (import.meta.env.DEV) {
      const devUser = {
        id: 1,
        username: 'dev-admin',
        email: 'dev@admin.com',
        role: 'admin'
      }
      currentUser.value = devUser
      userPermissions.value = getUserPermissions('admin')
      return
    }

    const savedUser = localStorage.getItem('currentUser')
    const savedPermissions = localStorage.getItem('userPermissions')
    
    if (savedUser) {
      currentUser.value = JSON.parse(savedUser)
    }
    if (savedPermissions) {
      userPermissions.value = JSON.parse(savedPermissions)
    }
  }

  // 检查是否有权限
  const hasPermission = (permission) => {
    return userPermissions.value.includes(permission)
  }

  // 检查是否有任一权限
  const hasAnyPermission = (permissions) => {
    return permissions.some(permission => userPermissions.value.includes(permission))
  }

  // 检查是否有所有权限
  const hasAllPermissions = (permissions) => {
    return permissions.every(permission => userPermissions.value.includes(permission))
  }

  // 根据角色获取权限
  const getUserPermissions = (role) => {
    const rolePermissions = {
      admin: [
        'user:create', 'user:read', 'user:update', 'user:delete',
        'role:create', 'role:read', 'role:update', 'role:delete',
        'system:config', 'system:log', 'system:monitor'
      ],
      editor: [
        'user:read', 'user:update',
        'role:read'
      ],
      viewer: [
        'user:read',
        'role:read'
      ]
    }
    return rolePermissions[role] || []
  }

  // 计算属性
  const isLoggedIn = computed(() => !!currentUser.value)
  const userRole = computed(() => currentUser.value?.role || '')

  return {
    currentUser,
    userPermissions,
    isLoggedIn,
    userRole,
    login,
    logout,
    initAuth,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions
  }
}
